#include <string.h>
#include <stdlib.h>
#include "bigNumber.h"

char* removeSpace(char* number)
{
    //if( strcmp(number,NULL)==0)
    //    return NULL;
    int i,j, len = strlen(number);
    char* copystr = (char*)malloc(sizeof(char)*len);
    for(i=0,j=0; i<=len; i++)
    {
        if(number[i]!=' ')
        {
            copystr[j] =  number[i];
            j++;
        }
    }
    return copystr;
}

char* inverseString(char* number)
{
    int i, len = strlen(number);
    for(i=0; i<len/2; i++)
    {
        int x = number[i];
        number[i] = number[len-i-1];
        number[len-i-1] = x;
    }

    return number;
}

int validateNumber(char* number)
{
    char* str = removeSpace(number);

    int i, len=strlen(str);
    if((str[0]<48 || str[0]>57) && str[0]!='-')
        return 0;

    for(i=1; i<len; i++)
    {
        if(str[i]<48 || str[i]>57)
            return 0;
    }

    return 1;
}

char* getSum(char* numberOne, char* numberTwo)
{
    char* number1 = removeSpace(numberOne);
    char* number2 = removeSpace(numberTwo);

    if(!validateNumber(number1)||!validateNumber(number2))
        return "input invalid";

        //if number1<0 and number2>0 -> move to get subtraction
        //if number1>0 and number2<0 -> move to get subtraction
        //if number1<0 and number2<0 -> change sign before get sum and add sign

    int i,j,k, len1 = strlen(number1), len2 = strlen(number2);
    int remain=0;
    char* result = (char*)malloc(sizeof(char)*( len1 > len2 ? len1 + 1 : len2 + 1));

    for(i=len1-1, j=len2-1, k=0; i>=0 && j>=0; i--,j--)
    {
        int num = number1[i]+number2[j]-48+ remain;
        remain = num > 57 ? 1 : 0;
        num-=( num > 57 ? 10 : 0);

        result[k] = num;
        k++;
    }


    if(len1==len2 && remain)
        result[k++] =49; //number 1
    else if(len1>len2)
        while(i>=0)
        {
            int num = number1[i] + remain;
            remain = num > 57 ? 1 : 0;
            num-=( num > 57 ? 10 : 0);

            result[k]= num;
            k++;
            i--;
        }
    else if(len2>len1)
        while(j>=0)
        {
            int num = number2[j] + remain;
            remain = num > 57 ? 1 : 0;
            num-=( num > 57 ? 10 : 0);

            result[k]= num;
            k++;
            j--;
        }

    result[k] =0;

    return inverseString(result);
}
